package com.situ.springboot.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.situ.springboot.constant.RedisConstants;
import com.situ.springboot.mapper.BlogMapper;
import com.situ.springboot.pojo.Blog;
import com.situ.springboot.pojo.query.BlogQuery;
import com.situ.springboot.service.IBlogService;
import com.situ.springboot.util.PageResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Transactional
@Service
public class BlogServiceImpl implements IBlogService {
    private static final Logger logger = LoggerFactory.getLogger(BlogServiceImpl.class);
    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    private BlogMapper blogMapper;

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public PageResult list(BlogQuery blogQuery) {
        //记录开始时间
        //long begin = System.currentTimeMillis();

        //List<Blog> list = blogMapper.list(blogQuery);
        //int totalCount = blogMapper.selectTotalCount(blogQuery);
        PageHelper.startPage(blogQuery.getPage(), blogQuery.getLimit());
        List<Blog> list = blogMapper.list(blogQuery);
        PageInfo pageInfo = new PageInfo(list);
        int totalCount = (int) pageInfo.getTotal();

        /*//模拟一个耗时的操作
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        //记录结束时间
        long end = System.currentTimeMillis();
        long takeTime = end - begin;
        //严重程度： error>warn>info
        if (takeTime > 3000) {
            logger.error("========执行结束，耗时{}毫秒=========", takeTime);
        } else if (takeTime > 2000) {
            logger.warn("========执行结束，耗时{}毫秒=========", takeTime);
        } else {
            logger.info("========执行结束，耗时{}毫秒=========", takeTime);
        }*/

        return new PageResult(0, "", totalCount, list);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void add(Blog blog) {
        //int i = 3 / 0;
        blogMapper.add(blog);

        //将Blog中真正使用的图片放到Redis中
        redisTemplate.opsForSet().add(RedisConstants.UPLOAD_IMAGE_TO_DB, blog.getImage());
    }
}
